package com.peiwangroup.messageservice.controller;

import com.peiwangroup.messageservice.model.WeChatMessage;
import com.peiwangroup.messageservice.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/wechat")
public class WeChatMessageController {
    private static final Logger logger = LoggerFactory.getLogger(WeChatMessageController.class);
    
    @Autowired
    private MessageService messageService;
    
    @PostMapping("/message")
    public ResponseEntity<?> receiveMessage(@RequestBody WeChatMessage message) {
        try {
            logger.info("收到消息: messageId={}, type={}", message.getMessageId(), message.getMessageType());
            logger.debug("消息内容: {}", message.getContent());
            
            messageService.saveMessage(message);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "消息处理成功");
            response.put("messageId", message.getMessageId());
            return ResponseEntity.ok().body(response);
        } catch (Exception e) {
            logger.error("处理消息失败: " + e.getMessage(), e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(error);
        }
    }

    @PostMapping("/msg/receive")
    public ResponseEntity<?> receiveWeChatMsg(@RequestBody String rawMessage) {
        try {
            logger.info("收到微信消息: {}", rawMessage);
            WeChatMessage message = messageService.parseWeChatMessage(rawMessage);
            messageService.saveMessage(message);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "消息处理成功");
            response.put("messageId", message.getMessageId());
            return ResponseEntity.ok().body(response);
        } catch (Exception e) {
            logger.error("处理微信消息失败: " + e.getMessage(), e);
            Map<String, Object> error = new HashMap<>();
            error.put("success", false);
            error.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(error);
        }
    }
}